#!/bin/bash

# 生成告警信息通用脚本，包括产生告警与恢复告警

# 系统ID
system_id=$(cat config.cnf | grep SystemId | awk -F "=" '{print $2}')
# 告警存放文件夹
alert_dir=$(cat config.cnf | grep AlertDir | awk -F "=" '{print $2}')
http_server=$(cat config.cnf | grep HttpServer | awk -F "=" '{print $2}')
http_username=$(cat config.cnf | grep HttpUsername | awk -F "=" '{print $2}')
http_password=$(cat config.cnf | grep HttpPassword | awk -F "=" '{print $2}')
local_ip=$(hostname -I | awk '{print $1}')

# 生成告警
gen_alarm() {
    alarm_type=$1
    alert_content=$2
    alert_severity=$3
    component=$4
    state_file_name=$5
    alarm_file_tmp=$6
    uid=$([[ -f "state/${state_file_name}.txt" ]] && cat state/${state_file_name}.txt || uuidgen | sed 's/-//g')
    alarm=""${system_id}"|+|"$uid"|+|"$(date +'%Y%m%d%H%M%S')"|+|"${alarm_type}"|+|"${alert_content}"|+|"${alert_severity}"|+||+|"${local_ip}"|+|cmp|+|"${component}"|-|"
    echo ${alarm} >>${alarm_file_tmp}
    # 记录告警状态
    echo "${uid}" >state/${state_file_name}.txt
}

# 恢复告警
restore_alarm() {
    alarm_type=$1
    alert_content=$2
    component=$3
    state_file_name=$4
    alarm_file_tmp=$5
    if [[ -f "state/"${state_file_name}".txt" ]]; then
        uid=$(cat state/${state_file_name}.txt)
        if [[ ${uid} != '' ]]; then
            # 使用原告警id恢复告警
            re_alarm=""${system_id}"|+|"${uid}"|+|"$(date +'%Y%m%d%H%M%S')"|+|"${alarm_type}"|+|"${alert_content}"|+|0|+||+|"${local_ip}"|+|cmp|+|"${component}"|-|"
            echo ${re_alarm} >>${alarm_file_tmp}
            # 消除告警状态
            rm -f state/${state_file_name}.txt
        fi
    fi
}

# 发送告警
send_alarm() {
    alarm_file_tmp=$1
    # 将缓存告警放入告警文件夹
    alarm_count=$([[ -f ${alarm_file_tmp} ]] && cat ${alarm_file_tmp} | wc -l || echo 0)
    if [[ ${alarm_count} > 0 ]]; then
        alert_name=${system_id}_$(date +%s000)_${alarm_count}.txt
        cp ${alarm_file_tmp} ${alert_dir}/${alert_name}
        curl -u ${http_username}:${http_password}  -F "file=@${alert_dir}/${alert_name}" ${http_server}/${alert_name}
    fi
}

if [[ $1 == '-g' ]]; then
    gen_alarm $2 $3 $4 $5 $6 $7
elif [[ $1 == '-r' ]]; then
    restore_alarm $2 $3 $4 $5 $6
elif [[ $1 == '-s' ]]; then
    send_alarm $2
fi
